package com.example.javawebdemo.filters;

// AbstractValidationFilter.java

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
4.模板方法模式 (Template Method) - Filter通用逻辑
7. 职责链模式 (Chain of Responsibility) - Filter链条
// FilterChain 已由Servlet容器实现，天然支持职责链
 */

public abstract class AbstractValidationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 1. 前置条件检查
        if (!shouldFilter(request)) {
            chain.doFilter(req, resp);
            return;
        }

        // 2. 执行验证逻辑
        if (validate(request)) {
            chain.doFilter(req, resp);
        } else {
            handleValidationFailure(request, response);
        }
    }

    /**
     * 是否需要处理该请求（过滤判定条件）
     */
    protected abstract boolean shouldFilter(HttpServletRequest request);

    /**
     * 具体的验证逻辑（比如参数校验、权限校验）
     */
    protected abstract boolean validate(HttpServletRequest request);

    /**
     * 处理验证失败时的响应
     */
    protected abstract void handleValidationFailure(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws IOException, ServletException;
}
